package com.woniuxy.lab.woniu_lab_boss.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.lab.woniu_lab_boss.controller.form.AddPortForm;
import com.woniuxy.lab.woniu_lab_boss.exception.WebException;
import com.woniuxy.lab.woniu_lab_boss.exception.WebExceptionCode;
import com.woniuxy.lab.woniu_lab_boss.model.Port;
import com.woniuxy.lab.woniu_lab_boss.dao.PortDao;
import com.woniuxy.lab.woniu_lab_boss.model.User;
import com.woniuxy.lab.woniu_lab_boss.service.PortService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.lab.woniu_lab_boss.service.dto.PortDto;
import com.woniuxy.lab.woniu_lab_boss.service.dto.UserDto;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 端口表 服务实现类
 * </p>
 *
 * @author Silas
 * @since 2023-03-15
 */
@Service
public class PortServiceImpl extends ServiceImpl<PortDao, Port> implements PortService {
    @Resource
    private PortDao portDao;

    @Override
    public IPage<PortDto> findAll(Integer page, Integer size) {
        IPage<Port> iPage = new Page<>(page == null ? 1 : page, size == null ? 10 : size);
        IPage<Port> page1 = portDao.selectPage(iPage, new QueryWrapper<Port>());
        return page1.convert(u -> {
            PortDto portDto = new PortDto();
            BeanUtils.copyProperties(u, portDto);
            return portDto;
        });
    }

    @Override
    public IPage<PortDto> queryByCondition(Integer page, Integer size, String condition) {
        IPage<Port> iPage = new Page<>(page == null ? 1 : page, size == null ? 10 : size);
        IPage<Port> page1 = portDao.selectPage(iPage, new QueryWrapper<Port>().eq("type", condition));
        return page1.convert(u -> {
            PortDto portDto = new PortDto();
            BeanUtils.copyProperties(u, portDto);
            return portDto;
        });
    }

    @Override
    public void addPort(AddPortForm addPortForm) {
        Port port = portDao.selectOne(new QueryWrapper<Port>().eq("port", addPortForm.getPort()));
        if (port != null) throw new WebException(WebExceptionCode.PORT_IS_EXISTS);
        Port newPort = BeanUtil.copyProperties(addPortForm, Port.class);
        save(newPort);
    }

    @Override
    public void modifyPort(Integer portId, String port, String type) {
        Port byId = getById(portId);
        byId.setPort(port);
        byId.setType(type);
        updateById(byId);
    }
}
